#include"hook.h"
#include"iomanager.h"
#include"log.h"
#include<string.h>
#include <arpa/inet.h>


yuechuan::Logger::ptr g_logger = YUECHUAN_LOG_NAME("system");

void test_sleep() {
    yuechuan::IOManager iom(1);
    iom.schedule([]() {
        sleep(2);
        YUECHUAN_LOG_INFO(g_logger) << "sleep 2";
    });

    iom.schedule([]() {
        sleep(3);
        YUECHUAN_LOG_INFO(g_logger) << "sleep 3";
    });
    YUECHUAN_LOG_INFO(g_logger) << "test hook";

}

void test_sock() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(80);
    inet_pton(AF_INET, "14.215.177.39", &serverAddr.sin_addr.s_addr);
    YUECHUAN_LOG_DEBUG(g_logger) << "begin connect";
    int rt = connect(sock, (const sockaddr *) &serverAddr, sizeof(serverAddr));
    YUECHUAN_LOG_DEBUG(g_logger) << "connect rt = " << rt << " errno = " << errno;
    if (rt) {
        return;
    }
    YUECHUAN_LOG_DEBUG(g_logger) << " after connect";
    const char data[] = "GET / HTTP/1.0\r\n\r\n";
    rt = send(sock, data, sizeof(data), 0); /// 成功返回值为发送的字节数
    YUECHUAN_LOG_DEBUG(g_logger) << "send rt = " << rt << " errno = " << errno;
    if (rt <= 0) {
        return;
    }
    std::string buff;
    buff.resize(4096);
    rt = recv(sock, &buff[0], buff.size(), 0);
    YUECHUAN_LOG_DEBUG(g_logger) << "recv rt = " << rt << " errno = " << errno;
    if (rt <= 0) {
        return;
    }
    buff.resize(rt);
    YUECHUAN_LOG_INFO(g_logger) << buff;


}

int main(int argc, char **argv) {
//     test_sleep();
//    test_sock();
    yuechuan::IOManager iom;
    iom.schedule(test_sock);
    // test_sock();


    return 0;
}